//
//  HMNavigationController.swift
//  Weibo
//
//  Created by Apple on 2017/7/21.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit

class HMNavigationController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //  设置边缘手势代理
        self.interactivePopGestureRecognizer?.delegate = self
        
    }

    //  监听push操作
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        
        //  push的时候不是根视图控制器，隐藏tabbar
        if viewControllers.count > 0 {
            //  会出现阴影效果
            //  解决办法：1. 设置window的背景色，2.设置tabbar的背景图片
            viewController.hidesBottomBarWhenPushed = true
        }
        
        super.pushViewController(viewController, animated: animated)
        //  从第二级控制器开始判断，根视图控制器不设置
        if viewControllers.count > 1 {
            if viewControllers.count == 2 {
                //  获取第一级控制器
                let firstVC = viewControllers.first!
                //  获取标题
                let title = firstVC.title!
                
                //  设置导航栏左侧按钮
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
                //  设置标题
                viewController.title = "当前显示的是第\(viewControllers.count)级控制器"
                
            } else {
                //  设置导航栏左侧按钮
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
                //  设置标题
                viewController.title = "当前显示的是第\(viewControllers.count)级控制器"
                
            }
        }
        
        
    }
    
    //  MARK:   --返回操作
    @objc private func backAction() {
        self.popViewController(animated: true)
    }
   

}

//  MARK:   --手势代理
extension HMNavigationController: UIGestureRecognizerDelegate {
    //  是否开启边缘手势
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if viewControllers.count == 1 {
            //  根视图不开启边缘手势
            return false
        }
        return true
    }
}

